//
//  LXNetworkTools.swift
//  weibo
//
//  Created by 罗心 on 16/6/28.
//  Copyright © 2016年 罗心. All rights reserved.
//

import UIKit
import AFNetworking


enum MethodType: String {
    case GET = "GET"
    case POST = "POST"
}

class LXNetworkTools: AFHTTPSessionManager {
    

    static let sharedTools:LXNetworkTools = {
        let tools = LXNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    

    typealias SuccessClosure = (response: AnyObject?)->()
    typealias FailureClosure = (error: NSError)->()
    
    
    func request(method:MethodType, urlString: String, parameters: AnyObject?, success: SuccessClosure, failure: FailureClosure){
        // GET 请求
        if method == .GET {
            self.GET(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error: err)
                    
            })
        }else {
            // POST 请求
            self.POST(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error: err)
                    
            })
        }
    }


}


extension LXNetworkTools {

    func oauthLoadUserAccount(code: String, success: SuccessClosure, failure: FailureClosure){

        let urlString = "https://api.weibo.com/oauth2/access_token"

        let params = [
            "client_id":APPKEY,
            "client_secret":APPSECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":REDIRECT_URI
        ]
        
        self.request(MethodType.POST, urlString: urlString, parameters: params, success: success, failure: failure)
    }
    // 请求个人数据
    func oauthLoadUserInfo(userAccont: LXUserAccount, success: SuccessClosure, failure: FailureClosure) {

        let urlString = "https://api.weibo.com/2/users/show.json"

        let params = [
            "access_token":userAccont.access_token!,
            "uid":userAccont.uid!
        ]
        
        self.request(MethodType.GET, urlString: urlString, parameters: params, success: success, failure: failure)
    }
}
// 请求首页数据
extension LXNetworkTools {
    func homeLoadStatusData(success: SuccessClosure, failure: FailureClosure){

        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"

        let params = ["access_token": LXUserAccountTools.sharedTools.accessToken!]

        request(.GET, urlString: urlString, parameters: params, success: success, failure: failure)
    }
}

